<?php
namespace App\Services\WxCard\Factory;

use App\Models\WxCardExt;
use App\Facades\EasyWechat;
use App\Services\WxCard\WxCardService;
use App\Services\WxCommon\WxError;
/**
 * 折扣券
 * @package App\Services\WxCard
 */
class WxCardDiscount extends WxCardAbstract
{
    /**
     * 数据保存
     * @param $request
     * @return bool
     * @throws \Exception
     */
    public function save($request)
    {
        \DB::beginTransaction();
        try {
            //保存卡券基础和高级数据
            $cardBaseId = $this->saveBase($request);
            //保存会员卡数据
            $extId = $request->ext['id'] ?? 0;
            if ($extId) {
                $extModel = WxCardExt::where('appid', $this->appid)->findOrFail($extId);
            } else {
                $extModel = new WxCardExt;
            }
            $extModel->appid = $this->appid;
            $extModel->card_base_id = $cardBaseId;
            $extModel->least_cost = (int) $request->ext['least_cost'] ?? 0;
            $extModel->reduce_cost = (int) $request->ext['reduce_cost'] ?? 0;
            $extModel->discount = (int) $request->ext['discount'] ?? 0;
            $extModel->deal_detail = $request->ext['deal_detail'] ?? '';
            $extModel->gift = $request->ext['gift'] ?? '';
            $extModel->default_detail = $request->ext['default_detail'] ?? '';
            $extModel->save();

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 发布
     * @param $cardBaseId
     * @throws \Exception
     */
    public function publish($cardBaseId)
    {
        $base = \App\Models\WxCardBase::with(['advance', 'ext'])->where('appid', $this->appid)->findOrFail($cardBaseId);
        $cardData = $base->toArray();
        //组装卡券公共接口提交数据
        $apiPostData = $this->buildCommonApiPostData($cardData);
        //组装代金券接口数据
        $extData = $cardData['ext'];
        if (empty($cardData['card_id'])){
            $apiPostData['discount'] = isset($extData['discount']) ? (int) $extData['discount'] : 0;
        }
        $app = EasyWechat::officialAccount($this->appid);
        //提交到微信接口创建或更新卡券信息，保存微信卡券ID
        if (empty($base->card_id)) {
            $apiRs = $app->card->create('DISCOUNT', $apiPostData);
            WxError::checkApiResponse($apiRs);
            if (empty($apiRs['card_id'])) {
                throw new \Exception('微信卡号生成失败');
            }
            $base->audit_status = WxCardService::CARD_STATUS_NOT_VERIFY;
            $base->card_id = $apiRs['card_id'];
            $base->save();
        } else {
            $apiRs = $app->card->update($base->card_id, 'DISCOUNT', $apiPostData);
            WxError::checkApiResponse($apiRs);
            $base->audit_status = $apiRs['send_check'] == true ? WxCardService::CARD_STATUS_NOT_VERIFY : WxCardService::CARD_STATUS_VERIFY_OK;
            $base->save();
        }
        return true;
    }

    /**
     * 同步卡券信息
     * @param $cardInfo
     * @return bool
     * @throws \Exception
     */
    public function sync($cardInfo)
    {
        \DB::beginTransaction();
        try {
            //同步基础数据
            $cardBaseId = $this->syncBase($cardInfo);
            //卡券类型
            $cardType = !empty($cardInfo['card_type']) ? $cardInfo['card_type'] : '';
            $dataIndex = strtolower($cardType);
            $cardInfo = !empty($cardInfo[$dataIndex]) ? $cardInfo[$dataIndex] : [];
            //同步代金券
            $extModel = WxCardExt::where('appid', $this->appid)->where('card_base_id', $cardBaseId)->first();
            if (empty($extModel)) {
                $extModel = new WxCardExt;
            }
            $extModel->appid = $this->appid;
            $extModel->card_base_id = $cardBaseId;
            $extModel->discount = isset($cardInfo['discount']) ? (int) $cardInfo['discount'] : '';
            $extModel->save();

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 刷新领卡用户数据
     * @param $cardId
     * @param $userCode
     */
    public function upsetUserinfo($cardId, $userCode)
    {
        // TODO: Implement upsetUserinfo() method.
    }
}